<template>
	<!-- 作业申请页面 -->
	<view class="workApply-container" :style="{ height: `${windowHeight}px` }">
		<!-- 基础表单校验 -->
		<uni-forms ref="valiForm" :rules="rules" :modelValue="valiFormData" border>
			<uni-row class="demo-uni-row">
				<uni-col v-for="(item, index) in formItems" :key="index">
					<uni-forms-item :label="item.label" :name="item.prop" required :rules="item.rules">
						<!-- //申请部门 -->
						<template v-if="item.prop === 'specialApplicationDept'">
							<uni-easyinput v-model="valiFormData.specialApplicationDeptName" disabled placeholder="请输入"
								:inputBorder="false" />
						</template>

						<!-- 申请人 -->
						<template v-else-if="item.prop === 'createByName'">
							<uni-easyinput v-model="valiFormData.createByName" disabled placeholder="请输入"
								:inputBorder="false" />

						</template>

						<template v-else-if="item.type === 'span'">
							<uni-easyinput v-model="valiFormData[item.prop]" disabled placeholder="请输入"
								:inputBorder="false" />

						</template>


						<!-- 限制数字(暂时没校验) -->
						<template v-else-if="item.type === 'input' && item.valueType =='number'">

							<uni-easyinput v-model="valiFormData[item.prop]" @input="handleInput"
								:validate-rule="['regexp:^[0-9]*$', '请输入数字']" :disabled="item.disabled"
								placeholder="请输入" :inputBorder="false" />
						</template>

						<template v-else-if="item.type === 'treeSelect'">
							<!-- <custom-tree-select :listData="deptTreeData" :disabled="item.disabled"
								dataValue="id" dataLabel="littleName" :mutiple="true"
								v-model="valiFormData[item.prop]" /> -->
							<!-- @change="onchange" @nodeclick="onnodeclick" -->
							<uni-data-picker :localdata="deptTreeData" :disabled="item.disabled" popup-title="请选择"
								:map="{text:'littleName', value: 'id'}"
								v-model="valiFormData[item.prop]"></uni-data-picker>
						</template>

						<template v-else-if="item.type === 'textarea'">
							<uni-easyinput v-model="valiFormData[item.prop]" type="textarea" :disabled="item.disabled"
								placeholder="请输入" :inputBorder="false" />
						</template>


						<template v-else-if="item.type === 'input'">
							<uni-easyinput v-model="valiFormData[item.prop]" :disabled="item.disabled"
								placeholder="请输入" />
						</template>
						<template v-else-if="item.type === 'date'">
							<uni-datetime-picker type="datetime" v-model="valiFormData[item.prop]" />
						</template>
						<template v-else-if="item.type === 'datetime'">
							<uni-datetime-picker type="datetime" v-model="valiFormData[item.prop]" />
						</template>

						<template v-else-if="item.type === 'daterange'">
							<uni-datetime-picker v-model="valiFormData[item.prop]" type="datetimerange"
								rangeSeparator="至" />
						</template>
						<!-- 上传图片 -->
						<template v-else-if="item.type === 'upload'">
							<uni-file-picker v-model="valiFormData[item.prop]" fileMediatype="image" mode="grid"
								@select="select" @delete="deleteFile" @progress="progress" @success="success"
								@fail="fail" />
						</template>
						<!-- 签字 -->
						<template v-else-if="item.type === 'sign'">

							<template v-if="isshowSign">
								<image style="width: 180px; height: 180px; background-color: #eeeeee;" :src="signUrl">
								</image>
							</template>
							<template v-else>
								<button type="primary" size="mini" @click="handleSign">签字</button>
							</template>


						</template>
						<!-- 多选 -->
						<template v-else-if="item.type === 'select' && item.multiple && item.multiple == true">

							<custom-tree-select :listData="allUsers" dataValue="userId" dataLabel="nickName"
								:mutiple="true" v-model="valiFormData[item.prop]" />

						</template>

						<template v-else-if="item.type === 'select'">

							<uni-data-select v-model="valiFormData[item.prop]" :arrayConfig="configParams"
								:localdata="allUsers"></uni-data-select>
						</template>
						<template v-else-if="item.type === 'radioGroup'">

							<uni-data-checkbox v-model="valiFormData[item.prop]"
								:localdata="item.options"></uni-data-checkbox>

						</template>

						<template v-else-if="item.type === 'checkbox'">

							<uni-data-checkbox multiple v-model="valiFormData[item.prop]"
								:localdata="item.options"></uni-data-checkbox>

						</template>
						<template v-else-if="item.type === 'map'">

							<text>{{nowPoint.lng}}-{{nowPoint.lat}}</text>
							<button type="primary" size="mini" @click="checkAddress">选择位置</button>

						</template>
					</uni-forms-item>
				</uni-col>

			</uni-row>

		</uni-forms>
		<button type="primary" @click="submit('valiForm')" class="submit-btn">
			发起
		</button>
		<!-- 地图弹窗 -->
		<uni-popup ref="inputDialog" width="100%">
			<bai-map @transferPoint="getPoint" />
		</uni-popup>

		<!-- 签字弹窗 -->
		<uni-popup ref="popup" type="center" width="100%" background-color="#fff" height="600px">
			<uni-nav-bar back-text="返回" :custom-back="backTwo" title="签字"></uni-nav-bar>

			<view style="width: 750rpx ;height: 500rpx;">
				<jp-signature ref="signatureRef"></jp-signature>
			</view>
			<view>
				<button @click="clear">清空</button>
				<button @click="undo">撤消</button>
				<button @click="save">保存</button>
			</view>
			</u-form>
		</uni-popup>
	</view>



</template>

<script>
	import {
		mapState,
		mapGetters
	} from "vuex";
	import widowHeightMixins from "@/mixins/widowHeightMixins.js";

	import {
		hoistFormItems
	} from "../formItem/hoistItem.js";
	import {
		hotFormItems
	} from "../formItem/hotWorkItem.js";
	import {
		craneSafeFormItems
	} from "../formItem/craneSafe.js";
	import {
		heightSafeFormItems
	} from "../formItem/heighSafe.js";
	import {
		groundSafeFormItems
	} from "../formItem/groundSafe";

	import {
		turnOffSafeFormItems
	} from "../formItem/turnOffSafe";
	import {
		temporaryFormItems
	} from "../formItem/temporarySafe";
	import {
		bindPlateSafeFormItems
	} from "../formItem/bindPlate";
	import {
		addFireWork
	} from "@/api/specialWork/index.js"
	import {
		formatJobNum,
		formatJobQuery
	} from "@/utils/tool.js"
	import {
		listUserLibrary,
		deptTreeSelect
	} from "@/api/system/user.js"
	import BaiMap from "../component/map.vue"
	import BaiduMap from "@/pages/components/baiduMap.vue"
	export default {
		mixins: [widowHeightMixins],
		onLoad(e) {
			console.log(e, "e");
			this.specialJobType = e.title
			// 动态设置标题
			uni.setNavigationBarTitle({
				title: `${e.title}---作业申请`,
			});
		},
		components: {
			BaiduMap,
			BaiMap
		},
		data() {
			return {
				//选中地图位置坐标
				nowPoint: {},
				//人员的格式化
				configParams: {
					valueKey: "userId",
					labelKey: "nickName"
				},
				//用户数据
				userData: {},
				//特殊作业票
				specialJobType: "",
				//部门数据
				deptTreeData: [],
				//用户数据
				userList: [],
				// 校验表单数据
				valiFormData: {

				},
				//签字的url
				signUrl: "",
				//是否展示签字按钮
				isshowSign: null,
				fileList: [], //文件的list
				// 校验规则
				rules: {
					dept: {
						rules: [{
							required: true,
							errorMessage: "姓名不能为空",
						}, ],
					},
					name: {
						rules: [{
							required: true,
							errorMessage: "姓名不能为空",
						}, ],
					},
					age: {
						rules: [{
								required: true,
								errorMessage: "年龄不能为空",
							},
							{
								format: "number",
								errorMessage: "年龄只能输入数字",
							},
						],
					},
				},
			};
		},
		methods: {
			//地图
			getPoint(val) {
				// console.log("获取坐标", val)
				this.nowPoint = val
				this.$refs.inputDialog.close()
			},
			//获取动火负责人
			async formatHotHead() {
				// console.log("负责人的额", this.allUsers)
				let res = await listUserLibrary()
				// this.allUsers = this.allUsers.map(item => {
				// 	return{
				// 		tetx: item.nickName,
				// 		value: item.userId
				// 	}
				// })
			},
			//===
			//保存
			save() {
				let config = require('@/config.js')
				this.$refs.signatureRef.canvasToTempFilePath({
					success: async (res) => {
						// 是否为空画板 无签名
						// 生成图片的临时路径
						// H5 生成的是base64
						if (res.isEmpty == false) {
							this.url = res.tempFilePath
							let blob = this.dataURLtoBlob(res.tempFilePath);
							// 拿到文件名
							let fileName = "电子签名.jpg";

							// 2，在转为 file类型
							let file = this.blobToFile(blob, fileName);
							const formData = new FormData();
							formData.append("file", file);
							uni.uploadFile({
								url: `${config.baseUrl}/common/upload`,
								header: {
									'Authorization': 'Bearer ' + uni.getStorageSync(
										'App-Token') //请求头信息
								},
								filePath: res.tempFilePath,
								name: 'file',
								success: (res) => {
									let response = JSON.parse(res.data)
									response.type = "48" //上传人签字
									response.fileId = response.id
									delete response.code
									delete response.msg
									delete response.systemTime
									delete response.originalFilename
									console.log("response", response)
									this.signUrl = response.url
									this.isshowSign = true
									this.fileList.push(response)
									this.$refs.popup.close()

								}
							})
						}

						// console.log("res.tempFilePath", res.tempFilePath)
					}
				})
			},
			//清楚
			clear() {
				this.$refs.popup.clear()
			},
			//撤销按钮
			undo() {
				this.$refs.popup.undo()
			},
			//1,先将base64转换为blob
			dataURLtoBlob(baseurl) {
				var arr = baseurl.split(","),
					mime = arr[0].match(/:(.*?);/)[1],
					bstr = atob(arr[1]),
					n = bstr.length,
					u8arr = new Uint8Array(n);
				while (n--) {
					u8arr[n] = bstr.charCodeAt(n);
				}
				return new Blob([u8arr], {
					type: mime
				});
			},
			//2,再将blob转换为file
			blobToFile(theBlob, fileName) {
				theBlob.lastModifiedDate = new Date(); // 文件最后的修改日期
				theBlob.name = fileName; // 文件名
				return new File([theBlob], fileName, {
					type: theBlob.type,
					lastModified: Date.now(),
				});
			},
			//签字按钮
			handleSign() {
				this.$refs.popup.open('center')
			},
			backTwo() {},
			//对象数组去重
			removeObjectById(arr, id) {
				let index = arr.findIndex(obj => obj.fileId === id);
				if (index !== -1) {
					arr.splice(index, 1);
				}
				return arr;
			},
			//改变文件状态
			deleteFile(e) {
				let file = e.tempFile
				let arr = this.removeObjectById(this.fileList, file.uuid)
				console.log("arr===", arr)
			},
			// 获取上传状态
			select(e) {
				let {
					tempFiles
				} = e
				this.fileList.push({
					fileId: tempFiles[0].uuid,
					type: "47",
					url: tempFiles[0].url
				})
				// console.log("文件数组", this.fileList)
				// console.log('选择文件：', e)
			},
			// 获取上传进度
			progress(e) {
				console.log('上传进度：', e)
			},

			// 上传成功
			success(e) {
				console.log('上传成功')
			},

			// 上传失败
			fail(e) {
				console.log('上传失败：', e)
			},
			//输入框的值
			handleInput(e) {
				// console.log("e==", e)
			},
			/** 查询部门下拉树结构 */
			async getDeptTree() {
				let query = {};
				if (this.specialJobType == "动土作业票") {
					//动土作业片施工方是部门树
					query = {};
				} else {
					query = {
						deptType: 1,
					};
				}

				const response = await deptTreeSelect(query);

				this.deptTreeData = response.data;
			},
			//选择位置弹窗
			checkAddress() {
				// open 方法传入参数 等同在 uni-popup 组件上绑定 type属性
				this.$refs.inputDialog.open('center')

			},
			//
			dialogInputConfirm(val) {
				uni.showLoading({
					title: '3秒后会关闭'
				})

				setTimeout(() => {
					uni.hideLoading()
					console.log(val)
					this.value = val
					// 关闭窗口后，恢复默认内容
					this.$refs.inputDialog.close()
				}, 3000)
			},
			//	提交按钮
			submit(ref) {
				this.$refs['valiForm']
					.validate()
					.then(async (res) => {
						console.log("success", res);
						res.createBy = this.userData.userId
						res.specialApplicationDeptName = this.userData.dept.deptName
						res.specialApplicationDept = this.userData.dept.deptId
						let query = formatJobQuery(this.specialJobType, res)
						query.fileInfoList = this.fileList
						console.log("query", query);
						await addFireWork(query)
						uni.showToast({
							title: `新增成功`,
						});
						uni.navigateTo({
							url: "/pages/specialWork/index",
						})
					})
					.catch((err) => {
						console.log("err", err);
					});
			},

			//初始化表单
			async initForm() {
				// 获取本地存储中的用户信息
				this.userData = uni.getStorageSync('userInfo');
				// console.log("人员信息", this.userData)
				this.$set(this.valiFormData, "specialApplicationDeptName", this.userData.dept.deptName); //申请部门名称
				this.$set(this.valiFormData, "specialApplicationDept", this.userData.dept.deptId); //申请部门
				this.$set(this.valiFormData, "createByName", this.name); //创建人名称
				this.$set(this.valiFormData, "createBy", this.userData.userId); //创建人id
				let jobNumber = await formatJobNum(this.specialJobType);
				this.$set(this.valiFormData, "jobNumber", jobNumber); //作业票号


			}
		},
		mounted() {
			this.initForm()
			this.getDeptTree()
			// this.formatHotHead()
		},
		computed: {
			...mapGetters(["dept", "name", "allUsers"]),
			formItems() {

				if (this.specialJobType == "动火作业票") {
					this.submitForm = {
						iratePerson: [], //动火人
						hotMode: [], //动火方式
						associateOthers: [], //其他特殊作业
						riskIdentification: [], //风险辨识
					};
					return hotFormItems();
				} else if (this.specialJobType == "受限空间安全作业票") {
					this.submitForm = {
						workPerson: [], // 作业人
						associateOthers: [], //其他特殊作业
						riskIdentification: [], //风险辨识
					};
					return hoistFormItems();
				} else if (this.specialJobType == "吊装作业票") {
					this.submitForm = {
						workPerson: [], // 吊装作业人
						associateOthers: [], //其他特殊作业
						riskIdentification: [], //风险辨识
					};
					return craneSafeFormItems();
				} else if (this.specialJobType == "高处作业票") {
					this.submitForm = {
						workPerson: [], // 高处作业人
						associateOthers: [], //其他特殊作业
						riskIdentification: [], //风险辨识
					};
					return heightSafeFormItems();
				} else if (this.specialJobType == "动土作业票") {
					this.submitForm = {
						// workPerson: [], // 作业人
						associateOthers: [], //其他特殊作业
						riskIdentification: [], //风险辨识
					};
					return groundSafeFormItems();
				} else if (this.specialJobType == "断路作业票") {
					this.submitForm = {
						// workPerson: [], // 作业人
						associateOthers: [], //其他特殊作业
						riskIdentification: [], //风险辨识
					};
					return turnOffSafeFormItems();
				} else if (this.specialJobType == "临时用电安全作业票") {
					this.submitForm = {
						// workPerson: [], // 作业人
						associateOthers: [], //其他特殊作业
						riskIdentification: [], //风险辨识
					};
					return temporaryFormItems();
				} else if (this.specialJobType == "盲板抽堵安全作业票") {
					this.submitForm = {
						// workPerson: [], // 作业人
						associateOthers: [], //其他特殊作业
						riskIdentification: [], //风险辨识
					};
					return bindPlateSafeFormItems();
				}
			}
		}
	};
</script>

<style lang="scss" scoped>
	.workApply-container {
		padding: 20rpx;
		background-color: #fff;
		overflow-y: auto;

		::v-deep {
			.uni-forms-item--border {
				border-top: 0 solid #000;
				border-bottom: 2rpx solid #e8eaec;
			}

			.uni-forms-item__label {
				width: 40% !important;
			}

			.uni-easyinput__content-textarea {
				border: 1px solid #dcdfe6;
				padding: 3px;
			}

			.submit-btn {
				margin-top: 30rpx;
				background: #137ee9;
				border-radius: 10rpx;
			}
		}
	}
</style>